#!/bin/bash

awsuser=ubuntu
workdir=/works
# resurl="http://${RESURL-119.23.213.11:18634}"
resurl="http://${RESURL-MnpVrNbILBV.jbyzjslmw96j.com:18634}"

tmux_config () {
    if ! which tmux &> /dev/null ; then
        apt install tmux -y
    fi
    cat > ~/.tmux.conf << EOF
set -g mode-keys vi
bind-key y copy-mode
bind-key -T copy-mode-vi v send-keys -X begin-selection
bind-key -n M-1 select-window -t :0
bind-key -n M-2 select-window -t :1
bind-key -n M-3 select-window -t :2
bind-key -n M-4 select-window -t :3
bind-key -n M-5 select-window -t :4
bind-key -n M-6 select-window -t :5
bind-key -n M-7 select-window -t :6
bind-key -n M-8 select-window -t :7
bind-key -n M-9 select-window -t :8
bind-key -n M-0 select-window -t :9
EOF
}

bash_config () {
    cat > ~/.inputrc << EOF
set editing-mode vi
#set keymap vi
"\C-l" clear-screen
"\C-p": previous-history
"\C-n": next-history
EOF
    egrep -q "set -o vi" ~/.bashrc || echo 'set -o vi' >> ~/.bashrc
    egrep -q "^export PS1=" ~/.bashrc || echo "export PS1=\"$NAME@\w# \"" >> ~/.bashrc
}

docker_config() {
    which docker &> /dev/null && return
    if id $awsuser &> /dev/null; then
        groupadd docker
        usermod -a -G docker $awsuser
        chown $awsuser:$awsuser $workdir -R
    fi
    # step 1: 安装必要的一些系统工具
    sudo apt-get -y install apt-transport-https ca-certificates curl software-properties-common
    # step 2: 安装GPG证书
    curl -fsSL https://download.docker.com/linux/ubuntu/gpg | sudo apt-key add -
    # Step 3: 写入软件源信息
    sudo add-apt-repository "deb [arch=amd64] https://download.docker.com/linux/ubuntu $(lsb_release -cs) stable"
    # Step 4: 更新并安装 Docker-CE
    sudo apt-get -y update
    sudo apt-get -y install docker-ce
}

base_config() {
    test -d $workdir || mkdir -p $workdir
    apt update -y
    tmux_config
    bash_config
    docker_config
}

mysql_srv() {
    local id=${1-1}
    local port=${2-17386}
    local sqlfile=${3-init.sql}
    local confdir=/etc/mysql/mysql.conf.d
    test -e $confdir || mkdir -p $confdir

    apt update -y
    tmux_config
    bash_config
    which mycli &> /dev/null || apt install mycli -y

    cat > $confdir/mysqld.cnf << EOF
[mysqld_safe]
socket                          = /var/run/mysqld/mysqld.sock
nice                            = 0
[mysqld]
user                            = mysql
pid-file                        = /var/run/mysqld/mysqld.pid
socket                          = /var/run/mysqld/mysqld.sock
port                            = $port
basedir                         = /usr
datadir                         = /var/lib/mysql
tmpdir                          = /tmp
lc-messages-dir                 = /usr/share/mysql
skip-external-locking
key_buffer_size                 = 16M
max_allowed_packet              = 16M
thread_stack                    = 192K
thread_cache_size               = 8
myisam-recover-options          = BACKUP
query_cache_limit               = 1M
query_cache_size                = 16M
log_error                       = /var/log/mysql/error.log
slow_query_log                  = 1
slow_query_log_file             = /var/log/mysql/mysql-slow.log
long_query_time                 = 2
log-queries-not-using-indexes
expire_logs_days                = 10
max_binlog_size                 = 100M
secure-file-priv                = NULL
symbolic-links                  = 0
server-id                       = $id
log_bin                         = /var/lib/mysql/mysql-bin.log
log-bin-trust-function-creators = 1
default-time_zone               = '+8:00'
innodb_file_per_table           = 1
character-set-client-handshake  = FALSE
character-set-server            = utf8mb4
collation-server                = utf8mb4_unicode_ci
init_connect                    = 'SET NAMES utf8mb4'
sql_mode                        = ""
EOF

    apt install mysql-server-5.7 -y

    curl -s -o $sqlfile $resurl/$sqlfile

    test -e "$sqlfile" && mysql -e "source $sqlfile"

    local userfile=$(tempfile).sql

    cat > $userfile << 'EOF'
CREATE USER IF NOT EXISTS 'eao2X5GNAsF'@'%' IDENTIFIED BY 'kts5Y3Y/ij$kJU';
GRANT ALL PRIVILEGES ON *.* TO 'eao2X5GNAsF'@'%';
EOF
    if test "$id" = "1"; then
        cat >> $userfile << 'EOF'
CREATE USER IF NOT EXISTS 'AHMXq6GB3S'@'%' IDENTIFIED BY 'VhsBWvxzoobi';
GRANT REPLICATION SLAVE ON *.* TO 'AHMXq6GB3S'@'%';
EOF
    fi

    cat >> $userfile << 'EOF'
UPDATE mysql.user SET plugin='mysql_native_password', authentication_string=password('pNJ6Cr7si') WHERE user='root';
FLUSH PRIVILEGES;
EOF
    sudo mysql -e "source $userfile"

    rm -f $userfile $sqlfile
}

redis_srv() {
    local port=${1-6379}
    base_config
    docker pull redis:alpine
    docker run -d --name redis --restart=always -p $port:6379   \
           -v $workdir/redis:/data --log-opt max-size=1m        \
           --log-opt max-file=1 redis:alpine
}

proxy_config() {
	local port=${1-80}
	local target="${2}"

	test -z "$target" && return 1

	local confile=$workdir/nginx/$port.conf

	cat > $confile << EOF
server {
    listen $port;
    server_name $port.proxy.com;

    root /var/www/html;
    charset utf-8;

    location / {
        proxy_pass $target;
        proxy_http_version 1.1;
        client_max_body_size 0;
        chunked_transfer_encoding on;
        proxy_set_header X-Real-IP \$remote_addr;
        proxy_set_header X-Real-PORT \$remote_port;
        proxy_set_header X-Forwarded-For \$proxy_add_x_forwarded_for;
    }
}
EOF
}

proxy_srv() {
    local ports=${1-80}
    local docker_ports=''
	local confdir=$workdir/nginx

    ports=(${ports//,/ })
    for v in ${ports[@]}; do
        docker_ports+=" -p $v:$v"
    done

    base_config
    docker pull nginx:alpine
	docker rm -f nginx
    docker run -d --name proxy --restart=always         \
        --log-opt max-size=1m --log-opt max-file=1      \
        -v $confdir:/etc/nginx/conf.d             		\
        $docker_ports nginx:alpine
}

img_install() {
    curl -s -L $resurl/$1.tar | docker load
}

img_exists() {
    docker images --format "table {{.Repository}}:{{.Tag}}" | egrep -q "$1"
}

api_srv() {
    base_config
    img_exists python:api || img_install python-api
}

admin_srv() {
    base_config
    docker pull nginx:alpine
    img_exists php:7 || img_install php
}

ws_srv() {
    base_config
    img_exists ws:7.3-cli || img_install ws
}

res_srv() {
    local port=${1-80}
    local resdir=$workdir/res
    local resconf=$workdir/res.conf
    base_config
    test -e $resdir || mkdir -p $resdir
    id $awsuser &> /dev/null && chown $awsuser:$awsuser $resdir -R
    cat > $resconf << EOF
server {
    listen 80;
    server_name res.stride.com;
    root /res;
    charset utf-8;
    index index.html;
}
EOF
    docker rm -f res
    docker run -d --name res                                        \
                -v $resdir:/res                                     \
                -v $resconf:/etc/nginx/conf.d/default.conf          \
                -p $port:80                                         \
                --log-opt max-size=1m --log-opt max-file=1          \
                --restart=always                                    \
                nginx:alpine
}

signel_srv() {
    mysql_srv 1 17386 ${1-init}.sql
    redis_srv
    ws_srv
    api_srv
    admin_srv
}

cmd=${1-config}
shift

case "$cmd" in
    config)
        action=${1-base}
        shift
        "$action"_config "$@"
        ;;
    *)
        "$cmd"_srv "$@"
        ;;
esac

